﻿/*
Copyright (c) 2011 <a href="http://www.gutgames.com">James Craig</a>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

#region Usings
using System;
using System.IO;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using Utilities.Compression.ExtensionMethods;
using Utilities.Web.ExtensionMethods;
using System.Web;
#endregion

namespace OptimizerPrime.BaseClasses
{
    /// <summary>
    /// Base class for pages
    /// </summary>
    public class BasePage : System.Web.UI.Page
    {
        #region Constructor

        /// <summary>
        /// Constructor
        /// </summary>
        public BasePage()
            : base()
        {
        }

        #endregion

        #region Protected Functions

        /// <summary>
        /// Loads the view state from the compressed format
        /// </summary>
        /// <returns>Returns the uncompressed view state</returns>
        protected override object LoadPageStateFromPersistenceMedium()
        {
            LosFormatter Formatter = new LosFormatter();
            string ZipState = Request.Form["__ZIPSTATE"];
            if (CompressViewState)
            {
                byte[] ZipStateBytes = Convert.FromBase64String(ZipState).Decompress();
                ZipState = Convert.ToBase64String(ZipStateBytes);
            }
            return Formatter.Deserialize(ZipState);
        }

        /// <summary>
        /// Compresses the view state down and saves it
        /// </summary>
        /// <param name="state">The view state object</param>
        protected override void SavePageStateToPersistenceMedium(object state)
        {
            LosFormatter Formatter = new LosFormatter();
            using (StringWriter Writer = new StringWriter())
            {
                Formatter.Serialize(Writer, state);
                byte[] StateBytes = Convert.FromBase64String(Writer.ToString());
                if (CompressViewState)
                    StateBytes = StateBytes.Compress();
                ScriptManager.RegisterHiddenField(this, "__ZIPSTATE", Convert.ToBase64String(StateBytes));
            }
        }

        /// <summary>
        /// OnLoad function
        /// </summary>
        /// <param name="e">EventArgs for loading the page</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            Compress();
        }

        #endregion

        #region Private Functions

        /// <summary>
        /// Goes through the header and adds the css
        /// handler to the header.
        /// </summary>
        private void Compress()
        {
            if (CompressCSS)
            {
                StringBuilder TempBuilder = new StringBuilder();
                string Splitter = "";
                for (int x = 0; x < Page.Header.Controls.Count; ++x)
                {
                    HtmlControl CurrentControl = Page.Header.Controls[x] as HtmlControl;
                    if (CurrentControl != null
                        && CurrentControl.Attributes["type"] != null
                        && CurrentControl.Attributes["type"].Equals("text/css", StringComparison.OrdinalIgnoreCase))
                    {
                        TempBuilder.Append(Splitter + CurrentControl.Attributes["href"]);
                        Page.Header.Controls.Remove(CurrentControl);
                        --x;
                        Splitter = ",";
                    }
                }
                LiteralControl Control = new LiteralControl("<link href=\"" + HttpContext.Current.AbsoluteRoot() + "CSS.ashx?Name=" + TempBuilder.ToString() + "\" type=\"text/css\" rel=\"stylesheet\" />");
                Control.EnableViewState = false;
                Page.Header.Controls.Add(Control);
            }
        }

        #endregion

        #region Properties

        protected virtual bool CompressViewState { get; set; }
        protected virtual bool CompressCSS { get; set; }

        #endregion
    }
}